﻿using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

[Serializable]
public class HexCoordinate
{
    [SerializeField]
    private int x,z;

    public int X { get { return x; } }	
    public int Z { get { return z; }  }
    public int Y { get { return -X - Z; } }

    public HexCoordinate(int x,int z)
    {
        this.x = x;
        this.z = z;
    }

    public static HexCoordinate FromPosition(Vector3 pos)
    {
        //int z = Mathf.FloorToInt(pos.z / (1.5f * HexMetrics.outerRadius));
        //int x = Mathf.FloorToInt((pos.x - (z % 2) * HexMetrics.innerRadius) / (HexMetrics.innerRadius * 2f));

        //HexCoordinate coord = new HexCoordinate(x, z);

        float x = pos.x / (HexMetrics.innerRadius * 2f);
        float y = -x;

        float offset = pos.y / (HexMetrics.outerRadius * 3f);
        x -= offset;
        y -= offset;

        int ix = Mathf.RoundToInt(x);
        int iy = Mathf.RoundToInt(y);
        int iz = Mathf.RoundToInt(-x - y);

        if (ix + iy + iz != 0)
        {
            float dX = Mathf.Abs(x - ix);
            float dY = Mathf.Abs(y - iy);
            float dZ = Mathf.Abs(-x - y - iz);
            if (dX > dY && dX > dZ)
            {
                ix = -iy - iz;
            }
            else if (dZ > dY)
            {
                iz = -ix - iy;
            }
        }
        

        return new HexCoordinate(ix,iz);
    }

    public static HexCoordinate FromOffsetCoordinates(int x, int z)
    {
        return new HexCoordinate(x - z/2, z);
    }

    public override string ToString()
    {
        return "(" + X.ToString() + "," + Y.ToString() +", " + Z.ToString() + ")";
    }

    public string ToStringOnSeparateLines()
    {
        return X.ToString() + "\n" + Y.ToString() + "\n" + Z.ToString();
    }
}

